package com.wangwenjun.concurrency.chapter17;

import java.util.ArrayList;
import java.util.List;

/**
 * 面试题: 写一个固定容量同步容器,拥有put和get方法,以及getCount方法,能够支持
 * 2个生产者线程和10个消费者线程的阻塞调用
 *
 * 使用wait和notify/notifyAll来实现
 */
public class TaoBaoTest3 {

    private List<String> list = new ArrayList<>();

    private static final int MAX = 10;


    public synchronized void put(){
        while (list.size() == MAX){
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        list.add(Thread.currentThread().getName());
        this.notifyAll();
    }


    public synchronized void get(){
        while (list.size() == 0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        this.notifyAll();
        String content = list.remove(0);
        System.out.println(Thread.currentThread().getName()+" consume:"+content);
    }

    public static void main(String[] args) {

        TaoBaoTest3 t = new TaoBaoTest3();

        new Thread(()->{
            for(;;){
                t.put();
            }
        }, "p0").start();


        new Thread(()->{
            for(;;){
                t.put();
            }
        }, "p1").start();


        for (int i = 0; i < 8; i++) {
            new Thread(()->{
                for(;;){
                    t.get();
                }
            }, "c"+i).start();
        }

    }


}
